package com.zmn.oms.business.impl.orderamount;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.price.common.constant.ItemCellConst;
import com.zmn.base.price.common.dto.ProductPriceDRO;
import com.zmn.base.price.dubbo.interfaces.calculate.ProductPriceRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.coa.common.dio.OrderAmountDIO;
import com.zmn.coa.common.dio.ProductInfoDIO;
import com.zmn.coa.common.dio.ThirdDiscountDetailDIO;
import com.zmn.coa.common.dro.ItemPriceCellDRO;
import com.zmn.coa.common.dro.OrderItem3PriceDRO;
import com.zmn.coa.common.enums.ThirdDiscountTypeEnum;
import com.zmn.coa.common.util.DubboConsts;
import com.zmn.coa.dubbo.impl.interfaces.amount.OrderAmountRemoteService;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.dms.common.dto.activity.dro.ActivityInfoDRO;
import com.zmn.dms.common.dto.preferential.dio.PromBaseRuleDIO;
import com.zmn.dms.dubbo.interfaces.activity.ActivityInfoListRemoteService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountBService;
import com.zmn.oms.common.constant.DiscountConsts;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dro.quotation3.EngineerDiscountDRO;
import com.zmn.oms.common.dro.quotation3.OrderAmountDRO;
import com.zmn.oms.common.dro.quotation3.OrderAmountDetailDRO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.orderamount.DiscountCalculateResultDTO;
import com.zmn.oms.model.dto.orderamount.DiscountDTO;
import com.zmn.oms.model.dto.orderamount.OrderAmountCalculateDTO;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.discount.OrderPayDiscount;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.quotation3.OrderQuotationProcess;
import com.zmn.oms.model.entity.quotation3.OrderQuotationServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.orderpaydiscount.OrderPayDiscountService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationProcessService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationServiceItemService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.vas.common.dro.CheckDRO;
import com.zmn.vas.dubbo.interfaces.order.VasOrderListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：计算金额
 *
 * @author heciqi
 * @date 2020/04/08 17:52
 */
@Service
@Slf4j
public class OrderAmountBServiceImpl implements OrderAmountBService {
    static final String TAG = "OMS-金额计算";

    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderDiscountService orderDiscountService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderQuotationServiceItemService orderQuotationServiceItemService;
    @Autowired
    OrderQuotationProcessService orderQuotationProcessService;
    @Autowired
    OrderServiceItemService orderServiceItemService;
    @Autowired
    OrderAmountBService orderAmountBService;

    @Reference(version = com.zmn.dms.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private ActivityInfoListRemoteService activityInfoListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private OrderAmountRemoteService orderAmountRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private VasOrderListRemoteService vasOrderListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private ProductPriceRemoteService productPriceRemoteService;
    @Autowired
    OrderPayDiscountService orderPayDiscountService;

    public void calculateOrderAmount(OrderAmountCalculateDTO orderAmountCalculateDTO) {

    }

    /**
     * 计算金额
     *
     * @param list
     * @param amount
     * @return
     */
    @Override
    public DiscountCalculateResultDTO calculateDiscount(List<DiscountDTO> list, Integer amount) {
        if (CollectionUtil.isNullOrEmpty(list) || NumberUtil.isNullOrZero(amount)) {
            return null;
        }

        // 优先--非折扣的优惠（立减，满减等）
        //List<DiscountDTO> collect = list.stream().filter(e -> !Objects.equals(e.getPreferentialType(), OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT)).collect(Collectors.toList());
        Integer discountAmt = 0;
        for (DiscountDTO discountDTO : list) {
            if (!Objects.equals(discountDTO.getPreferentialType(), OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT)) {
                discountAmt = discountAmt + discountDTO.getPreferentialValue();
                discountDTO.setDiscountAmount(discountAmt);
            }
        }

        // 折扣
        for (DiscountDTO discountDTO : list) {
            if (Objects.equals(discountDTO.getPreferentialType(), OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT)) {
                Integer tempDiscountAmt = MathUtil.sub(amount, discountAmt) * (MathUtil.sub(100, discountDTO.getPreferentialValue().intValue())) / 100;
                discountAmt += tempDiscountAmt;
                discountDTO.setDiscountAmount(tempDiscountAmt);
            }
        }

        Integer afterDiscountAmount;
        if (discountAmt > amount || discountAmt < 0) { // 优惠金额>原金额 或 优惠金额<0，优惠后金额为0
            afterDiscountAmount = 0;
        } else {
            afterDiscountAmount = MathUtil.sub(amount, discountAmt);
        }

        DiscountCalculateResultDTO build = DiscountCalculateResultDTO.builder()
                .afterDiscountAmount(afterDiscountAmount)
                .discountAmount(MathUtil.sub(amount, afterDiscountAmount))// 优惠金额 = 金额-优惠后金额
                .build();

        log.info("计算优惠输入list：{}amount：[{}]，输出[{}]", list, amount, build);
        return build;
    }

    public static void main(String[] args) {
        Integer tempDiscountAmt = MathUtil.sub(500, 0) * (MathUtil.sub(100, 90)) / 100;

        System.out.println();
    }

    /**
     * 获取产品价格
     *
     * @param cityId
     * @param channelId
     * @param showProductId
     * @return
     */
    @Override
    public ResponseDTO<ProductPriceDRO> getProductPriceDRO(Integer cityId, Integer channelId, Integer showProductId) {
        // 获取产品价格
        com.zmn.base.price.common.dto.ProductPriceQuery productPriceQuery = com.zmn.base.price.common.dto.ProductPriceQuery
                .builder()
                .channelId(channelId)
                .bizType(GlobalConsts.NO)
                .showType(BaseProductConsts.EC_SHOW_TYPE)
                .productIdList(Lists.newArrayList(showProductId))
                .cityId(cityId)
                .build();
        ResponseDTO<List<ProductPriceDRO>> listResponseDTO = productPriceRemoteService.listProductPriceByQuery(productPriceQuery);
        log.info("[{}] 查询产品价格入参[{}]，出参[{}]", TAG, JSON.toJSONString(productPriceQuery), JSON.toJSONString(listResponseDTO));
        if (!listResponseDTO.isSuccess()) {
            return com.zmn.common.dto2.ResponseDTO.fail(StringUtils.defaultIfBlank(listResponseDTO.getMessage(), "获取产品信息失败"));
        }

        // 无产品信息
        List<ProductPriceDRO> data = listResponseDTO.getData();
        if (CollectionUtil.isNullOrEmpty(data)) {
            log.info("无产品信息");
            return com.zmn.common.dto2.ResponseDTO.success(null);
        }

        // 无产品价格原价，定金
        ProductPriceDRO productPriceDRO = data.get(0);
        if (productPriceDRO == null) {
            log.info("无产品价格");
            return com.zmn.common.dto2.ResponseDTO.success(null);
        }

        if (NumberUtil.isNotNullOrZero(productPriceDRO.getPrice())) {
            return com.zmn.common.dto2.ResponseDTO.success(productPriceDRO);
        }
        List<Integer> needPay = Arrays.asList(1);// 是否需要支付
        if (NumberUtil.isNotNullOrZero(productPriceDRO.getDeposit()) && needPay.contains(productPriceDRO.getPayType())) {
            return com.zmn.common.dto2.ResponseDTO.success(productPriceDRO);
        }
        return com.zmn.common.dto2.ResponseDTO.success(null);
    }

    /**
     * 获取一口价优惠
     *
     * @param productPriceDRO
     * @return
     */
    @Override
    public DiscountDTO getFinalPriceDiscount(ProductPriceDRO productPriceDRO) throws OmsBaseException {
        if (productPriceDRO == null) {
            return null;
        }
        // 非一口价没一口价优惠
        if (!Objects.equals(productPriceDRO.getItemStandard(), GlobalConsts.YES)) {
            return null;
        }

        // 后付，没有一口价优惠
        if (Objects.equals(productPriceDRO.getPayType(), 2)) {
            return null;
        }

        // 有定金，没有一口价优惠
        if (NumberUtil.isNotNullOrZero(productPriceDRO.getDeposit())) {
            return null;
        }

        final Integer activityId = 10002;
        com.zmn.common.dto2.ResponseDTO<ActivityInfoDRO> activityInfoResponseDTO = activityInfoListRemoteService.getActivityDescById(activityId);
        log.info("[{}] 查询活动优惠入参[{}]，出参[{}]", TAG, activityId, JSON.toJSONString(activityInfoResponseDTO));
        if (!activityInfoResponseDTO.isSuccess() || activityInfoResponseDTO.getData() == null) {
            throw new OmsBaseException("支付优惠不可用");
        }
        DiscountDTO discountDTO = new DiscountDTO();
        discountDTO.setBatchId(activityId);
        discountDTO.setItemId(0);
        discountDTO.setItemCode("");
        discountDTO.setDiscountCateg(FicoConsts.ORDER_IN_DISCOUNT_CATEG_ACTIVITY);
        discountDTO.setPreferentialType(OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT);
        discountDTO.setPreferentialValue(90);//指定为9折
        discountDTO.setDiscountSourceData(JSON.toJSONString(activityInfoResponseDTO.getData()));
        log.info("[{}] 一口价-优惠[{}]", TAG, discountDTO);
        return discountDTO;
    }

    /**
     * 获取优惠券优惠
     *
     * @param cityId
     * @param channelId
     * @param showProductId
     * @param userId
     * @param itemCode
     * @param amount
     * @return
     */
    @Override
    public DiscountDTO getCouponDiscount(Integer cityId, Integer channelId, Integer showProductId, Long userId, String itemCode, Integer amount) throws OmsBaseException {
        if (NumberUtil.isNullOrZero(userId) || StringUtil.isBlank(itemCode)) {
            return null;
        }
        return null;

	/*	CoupItemDIO coupItemDIO = CoupItemDIO.builder().cityId(cityId)
				.channelId(channelId)
				.productId(showProductId)
				.userId(userId)
				.itemCode(itemCode)
				.amount(amount).build();
		com.zmn.common.dto2.ResponseDTO<CoupItemInfoDRO> coupInfoByItemCode = goupGetInfoRemoteService.getCoupInfoByItemCode(coupItemDIO);
		log.info("[{}] 查询优惠券入参[{}]，出参[{}]", TAG, JSON.toJSONString(coupItemDIO), JSON.toJSONString(coupInfoByItemCode));
		if (!coupInfoByItemCode.isSuccess() || coupInfoByItemCode.getData() == null) {
			log.error("goupGetInfoRemoteService#getCoupInfoByItemCode 错误[{}]", coupInfoByItemCode.getMessage());
			throw new OmsBaseException(StringUtils.defaultIfBlank(coupInfoByItemCode.getMessage(), "优惠券不可用"));
		}

		CoupItemInfoDRO coupItemInfoDRO = coupInfoByItemCode.getData();
		if (!Objects.equals(coupItemInfoDRO.getStatus(), GlobalConsts.YES)) {
			log.info("goupGetInfoRemoteService#getCoupInfoByItemCode 优惠状态不可用[{}]", coupItemInfoDRO.getStatus());
			throw new OmsBaseException("优惠券状态不可用");
		}

		DiscountDTO discountDTO = new DiscountDTO();
		discountDTO.setBatchId(coupItemInfoDRO.getBatchId());
		discountDTO.setItemId(coupItemInfoDRO.getItemId());
		discountDTO.setItemCode(coupItemInfoDRO.getItemCode());
		discountDTO.setDiscountCateg(FicoConsts.ORDER_IN_DISCOUNT_CATEG_COUPON);
		discountDTO.setPreferentialType(this.convertPreferentialType(coupItemInfoDRO.getPreferentialType()));
		discountDTO.setPreferentialValue(coupItemInfoDRO.getPreferentialValue());
		log.info("[{}] 优惠券-优惠[{}]", TAG, discountDTO);
		return discountDTO;*/
    }

    private Integer convertPreferentialType(Integer preferentialType) {
        if (Objects.equals(preferentialType, 1)) {
            return OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT;
        } else if (Objects.equals(preferentialType, 2)) {
            return OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE;
        } else {
            return GlobalConsts.NONE;
        }
    }

    /**
     * 获取支付金额
     *
     * @param productPriceDRO
     * @return
     */
    @Override
    public Integer getPayAmount(ProductPriceDRO productPriceDRO, Integer number) {
        if (productPriceDRO == null) {
            return null;
        }

        List<Integer> needPay = Arrays.asList(1);// 是否需要支付
        // 定金作为支付金额
        if (NumberUtil.isNotNullOrZero(productPriceDRO.getDeposit()) && needPay.contains(productPriceDRO.getPayType())) {
            return productPriceDRO.getDeposit() * number;
        }
        // 原价作为支付金额
        if (NumberUtil.isNotNullOrZero(productPriceDRO.getPrice())) {
            return productPriceDRO.getPrice() * number;
        }
        return null;
    }

    @Override
    public OrderAmountDRO getQuotationOrderAmountByOrderIdAndWorkId(Long orderId, Long workId, Integer engineerDiscountId) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException(OmsErrorCodeConsts.ORDER_NOT_FOUND, "订单不存在");
        }
        List<OrderProduct> orderProducts = orderProductService.listOrderProductByOrderId(orderId);

        List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderId);

        List<OrderPayDiscount> orderPayDiscountList = orderPayDiscountService.listOrderPayDiscountByOrderId(orderId);

        OrderQuotationProcess process = orderQuotationProcessService.findByOrderId(orderId);

        List<Integer> itemIds = Lists.newArrayList();
        List<OrderQuotationServiceItem> serviceItemList = orderQuotationServiceItemService.listByOrderId(orderId);
        if (CollectionUtil.isNullOrEmpty(serviceItemList)) {
            return null;
        }
        itemIds = serviceItemList.stream().map(OrderQuotationServiceItem::getItemId).collect(Collectors.toList());

        if (NumberUtil.isNullOrZero(engineerDiscountId)
                && NumberUtil.isNotNullOrZero(process.getEngineerDiscountId())
                && Objects.equals(process.getEngineerDiscountStatus(), GlobalConsts.YES)
                && !Objects.equals(process.getAgreeStatus(), GlobalConsts.NO)) {
            // 优先以传过来的为准
            engineerDiscountId = process.getEngineerDiscountId();
        }

        return this.getQuotationOrderAmount(orderWork, itemIds, orderProducts.get(0), orderDiscountList, engineerDiscountId, orderPayDiscountList);
    }

    @Override
    public OrderAmountDRO getQuotationOrderAmount(OrderWork orderWork, List<Integer> itemIdList, OrderProduct orderProduct, List<OrderDiscount> discountList, Integer engineerDiscountId, List<OrderPayDiscount> orderPayDiscountList) throws OmsBaseException {

        // 处理产品信息
        Integer showType = NumberUtil.isNotNullOrZero(orderProduct.getProductId()) ? BaseProductConsts.ERP_SHOW_TYPE : BaseProductConsts.EC_SHOW_TYPE;
        ProductInfoDIO productInfoDIO = ProductInfoDIO.builder()
                .showProductId(orderProduct.getShowProductId())
                .productId(orderProduct.getProductId())
                .productNum(orderProduct.getNumber())
                .brandId(orderProduct.getBrandId())
                .itemList(itemIdList)
                .categTwoId(orderProduct.getCategId())
                .showType(showType)
                .tariffId(orderProduct.getTariffId())
                .build();

        // tariffId

        List<ProductInfoDIO> productInfoList = Lists.newArrayList(productInfoDIO);

        PromBaseRuleDIO userSelect = null;
        AtomicReference<Integer> atomicReference = new AtomicReference<>();
        if (CollectionUtil.isNotNullOrEmpty(discountList)) {
            userSelect = new PromBaseRuleDIO();
            // 促销ID
            discountList.stream().filter(item -> {
                return Objects.equals(item.getCateg(), DiscountConsts.DISCOUNT_CATEG_PROM);
            }).findFirst().ifPresent(discount -> {
                atomicReference.set(discount.getItemId());
            });

            userSelect.setCodes(discountList.stream().filter(item -> {
                return !Objects.equals(item.getCateg(), DiscountConsts.DISCOUNT_CATEG_PROM);
            }).map(OrderDiscount::getItemCode).collect(Collectors.toList()));
            userSelect.setPromIds(discountList.stream().filter(item -> {
                return Objects.equals(item.getCateg(), DiscountConsts.DISCOUNT_CATEG_PROM);
            }).map(OrderDiscount::getItemId).collect(Collectors.toList()));
        }


        ResponseDTO<CheckDRO> checkDROResponseDTO = vasOrderListRemoteService.checkNineDollarsNine(orderWork.getUserId());
        if (!checkDROResponseDTO.isSuccess()) {
            throw new OmsBaseException("用户会员信息获取失败");
        }
        CheckDRO checkDRO = checkDROResponseDTO.getData();
        Integer isMember = GlobalConsts.NO;
        if (Objects.equals(isMember, GlobalConsts.YES) && DateUtil.getNow().before(checkDRO.getExpireTime())) {
            isMember = GlobalConsts.YES;
        }

        // 计算金额
        OrderAmountDIO orderAmountDIO = OrderAmountDIO.builder()
                .orderId(orderWork.getOrderId())
                .openVip(GlobalConsts.NO)
                .cityId(orderWork.getCityId())
                .channelId(orderWork.getChannelId())
                .bizType(orderWork.getBizType())
                .plat(orderWork.getPlat())
                .memberFlag(isMember)
                .userId(orderWork.getUserId())
                .promId(atomicReference.get())
                .productInfoList(productInfoList)
                .userSelect(userSelect)
                .invoker(1)
                .quoteType(1)
                .tariffOnoff(GlobalConsts.YES)
                .untariffOnoff(GlobalConsts.NO)
                .unUsePreferential(Objects.isNull(userSelect) ? GlobalConsts.NO : GlobalConsts.YES)
                .paidPrice(Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) ? orderWork.getPrepayAmount() : 0)
                .discountId(engineerDiscountId)
                .thirdDiscountList(this.convertToThirdDiscountDetailDIO(orderPayDiscountList))
                .build();
        //设置支付明细
        this.getListOrderPayDiscount(orderAmountDIO, orderWork.getOrderId());
        log.info("#[{}]调用价格计算服务 入参：{}", orderWork.getOrderId(), JSON.toJSONString(orderAmountDIO));
        ResponseDTO<com.zmn.coa.common.dro.OrderAmountDRO> amountResponse = orderAmountRemoteService.getOrderAmount(orderAmountDIO);
        log.info("#[{}]调用价格计算服务 出参：{}", orderWork.getOrderId(), JSON.toJSONString(amountResponse));

        if (!amountResponse.isSuccess() || Objects.isNull(amountResponse.getData())) {
            throw new OmsBaseException(OmsErrorCodeConsts.CALL_THIRED_SYS_FAILED, amountResponse.getMessage());
        }

        com.zmn.coa.common.dro.OrderAmountDRO coaOrderAmountDRO = amountResponse.getData();
        OrderItem3PriceDRO item3PriceDRO = coaOrderAmountDRO.getOrderItem3PriceDRO();

        OrderAmountDRO resultDRO = new OrderAmountDRO();
        resultDRO.setCoupDiscountAmount(item3PriceDRO.getCouponPrice());
        resultDRO.setOtherDiscountAmount(item3PriceDRO.getOtherDiscount());
        resultDRO.setDepositAmount(item3PriceDRO.getPaidPrice());
        resultDRO.setTotalFee(coaOrderAmountDRO.getAmountPrice());
        int prepayAmount = Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) ? orderWork.getPrepayAmount() : 0;
        resultDRO.setRemainingReceivableAmount(orderWork.getTotalAmount() - prepayAmount);
        if (CollectionUtil.isNotNullOrEmpty(item3PriceDRO.getItemCellList())) {
            List<ItemPriceCellDRO> itemPriceCellDROS = item3PriceDRO.getItemCellList()
                    .stream()
                    .filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES))
                    .sorted(Comparator.comparing(ItemPriceCellDRO::getSort))
                    .collect(Collectors.toList());
            List<OrderAmountDetailDRO> itemCellList = new ArrayList<>(itemPriceCellDROS.size());
            for (ItemPriceCellDRO itemCell : itemPriceCellDROS) {
                OrderAmountDetailDRO detailDRO = new OrderAmountDetailDRO();
                detailDRO.setItemCellId(itemCell.getItemCellId());
                detailDRO.setItemCellName(itemCell.getItemCellName());
                detailDRO.setCellPrice(itemCell.getCellPrice());
                itemCellList.add(detailDRO);
                // 兼容老包
                switch (itemCell.getItemCellId()) {
                    case ItemCellConst.ITEM_CELL_PART:
                        resultDRO.setPartPrice(itemCell.getCellPrice());
                        break;
                    case ItemCellConst.ITEM_CELL_HOUR:
                        resultDRO.setHourFee(itemCell.getCellPrice());
                        break;
                    case ItemCellConst.ITEM_CELL_TRIP:
                        resultDRO.setTrafficFee(itemCell.getCellPrice());
                        break;
                }
            }
            resultDRO.setDetailList(itemCellList);
        }
        resultDRO.setServItemPrice(item3PriceDRO.getPrice());
        resultDRO.setServItemName(item3PriceDRO.getItemName());

        // 不同意不显示优惠金额
        OrderQuotationProcess process = orderQuotationProcessService.findByOrderId(orderWork.getOrderId());
        if (Objects.equals(process.getAgreeStatus(), GlobalConsts.NO)) {
            resultDRO.setOtherDiscountAmount(null);
        }


        return resultDRO;
    }

    @Override
    public EngineerDiscountDRO getOrderEngineerDiscount(Long orderId, Long workId) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException(OmsErrorCodeConsts.ORDER_NOT_FOUND, "订单不存在");
        }
        OrderQuotationProcess process = orderQuotationProcessService.findByOrderId(orderId);
        if (Objects.isNull(process) || NumberUtil.isNullOrZero(process.getEngineerDiscountId())) {
            throw new OmsBaseException(OmsErrorCodeConsts.STATUS_NOT_LEGAL, "工程师还未未用户选择优惠");
        }
        EngineerDiscountDRO engineerDiscountDRO = new EngineerDiscountDRO();
        engineerDiscountDRO.setChannelId(orderWork.getChannelId());
        engineerDiscountDRO.setCityId(orderWork.getCityId());
        engineerDiscountDRO.setProductId(orderWork.getShowProductId());
        engineerDiscountDRO.setPromId(process.getEngineerDiscountId());

        return engineerDiscountDRO;
    }

    @Override
    public Integer getOrderWorkFactAmount(OrderWork orderWork) {
        Integer factAmount = 0;
        if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getChannelPrepayAmount())) {
            factAmount = factAmount + orderWork.getChannelPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getPrepayAmount())) {
            factAmount = factAmount + orderWork.getPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getDepositAmount())) {
            factAmount = factAmount + orderWork.getDepositAmount().intValue();
        }
        if (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getMasterAmount())) {
            factAmount = factAmount + orderWork.getMasterAmount().intValue();
        }
        if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
            factAmount = MathUtil.sub(factAmount, orderWork.getRefundAmount());
        } else {
            if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) && !NumberUtil.isNullOrZero(orderWork.getRefundAmount())) {
                factAmount = MathUtil.sub(factAmount, orderWork.getRefundAmount());
            }
        }

        return factAmount;
    }

    @Override
    public Integer getOrderWorkRemainingReceivableAmount(OrderWork orderWork) {
        Integer totalAmount = Optional.ofNullable(orderWork.getTotalAmount()).orElse(0);
        Integer factAmount = this.getOrderWorkFactAmount(orderWork);

        // 应收-已付 = 剩余应收
        int remainingReceivableAmount = totalAmount - factAmount;
        log.info("#获取订单剩余应收金额 workId={},remainingReceivableAmount={}", orderWork.getWorkId(), remainingReceivableAmount);
        return remainingReceivableAmount;
    }

    private void getListOrderPayDiscount(OrderAmountDIO orderAmountDIO, Long orderId) {
        List<OrderPayDiscount> listOrderPayDiscount = orderPayDiscountService.listOrderPayDiscountByOrderId(orderId);
        if (CollectionUtil.isNotNullOrEmpty(listOrderPayDiscount)) {
            final List<ThirdDiscountDetailDIO> collect = listOrderPayDiscount.stream().map(x -> {
                ThirdDiscountDetailDIO thirdDiscountDetailDIO = new ThirdDiscountDetailDIO();
                thirdDiscountDetailDIO.setCoupCode(x.getCode());
                thirdDiscountDetailDIO.setThirdType(ThirdDiscountTypeEnum.ALIPAY.getKey());
                thirdDiscountDetailDIO.setDiscountPrice(x.getAmount());
                return thirdDiscountDetailDIO;
            }).collect(Collectors.toList());
            orderAmountDIO.setThirdDiscountList(collect);
        }
    }


    private List<ThirdDiscountDetailDIO> convertToThirdDiscountDetailDIO(List<OrderPayDiscount> orderDiscounts) {
        List<ThirdDiscountDetailDIO> list = Lists.newArrayList();
        for (OrderPayDiscount orderDiscount : orderDiscounts) {
            ThirdDiscountDetailDIO thirdDiscountDetailDIO = new ThirdDiscountDetailDIO();
            thirdDiscountDetailDIO.setCoupCode(orderDiscount.getCode());
            thirdDiscountDetailDIO.setDiscountPrice(orderDiscount.getAmount());
            thirdDiscountDetailDIO.setThirdType(ThirdDiscountTypeEnum.ALIPAY.getKey());
            list.add(thirdDiscountDetailDIO);
        }
        return list;
    }
}
